<template>
  <div>
    <div v-if="flag === 1" class="flex-box mb-10">
      <div class="flex-box-left">
        <el-form
          ref="form"
          :model="form"
          label-width="90px"
          :inline="true"
          class="wz-form"
          label-position="center"
        >
          <el-form-item
            label="物料编码:"
            prop="categoryCode"
            class="wz-el-form-item"
          >
            <el-input v-model="form.categoryCode" />
          </el-form-item>
          <el-form-item
            label="物料名称:"
            prop="categoryName"
            class="wz-el-form-item"
          >
            <el-input v-model="form.categoryName" />
          </el-form-item>
          <el-form-item
            label="申领单号:"
            prop="applySno"
            class="wz-el-form-item"
          >
            <el-input v-model="form.applySno" />
          </el-form-item>
          <el-form-item
            label="出库单编号:"
            prop="orderId"
            class="wz-el-form-item"
          >
            <el-input v-model="form.orderId" />
          </el-form-item>
        </el-form>
      </div>
      <div class="flex-box-right pb-5">
        <el-button
          class="pms-button-primary"
          @click="handleSearch"
        >查询</el-button>
        <el-button
          v-if="backMaterialState && !!+isNewPrj && isEdit && metaEdit"
          class="pms-button-primary"
          @click="handlePush"
        >物资信息同步资源</el-button>
      </div>
    </div>
    <el-row>
      <el-col :span="16">
        <wz-table
          :columns="wzApplicationColumnLeft"
          :use-index="true"
          :table-data="designData"
        >
          <!-- 设计数量 -->
          <!-- 累计申领数量 -->
          <template #header="{ col }">
            <div v-if="col.details" class="header-wrapper">
              <el-tooltip
                class="item"
                effect="dark"
                :content="col.details"
                placement="top-start"
              >
                <span> {{ col.label }}</span>
              </el-tooltip>
            </div>
            <div v-else class="header-wrapper">
              {{ col.label }}
            </div>
          </template>
          <template #ifSourceCode="{ row }">
            <div>
              {{ +row.ifSourceCode ? "否" : "是" }}
            </div>
          </template>
          <!-- 已出库数量 -->
          <template #amount="{ row }">
            <div
              v-if="
                +row.amount > 0 &&
                  flag === 1 &&
                  +row.assetLabelNum
              "
              class="click-row"
              @click="handleMaterialRemoveList(row)"
            >
              {{ row.amount }}
            </div>
            <div v-else>{{ row.amount || 0 }}</div>
          </template>
          <!-- 申请退库总数 -->
          <template #retreatAmount="{ row }">
            <div
              v-if="+row.retreatAmount >= 0 && flag === 1"
              class="click-row"
              @click="handleCancelRetreatApply(row)"
            >
              {{ retreatAmount(row) }}
            </div>
            <div v-else>{{ row.retreatAmount || 0 }}</div>
          </template>
        </wz-table>
        <div class="table-bottom-border" />
      </el-col>
      <el-col :span="8">
        <wz-table
          :columns="wzApplicationColumnRight"
          :table-data="designData"
        >
          <template #header="{ col }">
            <div v-if="col.details" class="header-wrapper">
              <el-tooltip
                class="item"
                effect="dark"
                :content="col.details"
                placement="top-start"
              >
                <span> {{ col.label }}</span>
              </el-tooltip>
            </div>
            <div v-else class="header-wrapper">
              {{ col.label }}
            </div>
          </template>
          <!-- 是否利旧资产 -->
          <template #outputType="{ row }">
            <div>
              {{ outputType(row) }}
            </div>
          </template>
          <template #operation="{ row }">
            <el-button-group>
              <el-button
                v-if="newPerissonShow&&+row.jwMateRetreat===1?newPower(row,'back'):checkIsRetreat(row) && isEdit && metaEdit"
                class="pms-button-primary mr-5"
                @click="handleCancelRetreatApply(row)"
              >撤销退库</el-button>
              <el-button
                v-if="
                newPerissonShow&&+row.jwMateRetreat===1?newPower(row,'apply'):
                  row.canRetreatAmount > 0 &&
                    backMaterialState &&
                    isEdit && metaEdit
                "

                class="pms-button-primary"
                @click="handleMaterialRemoveFormVisible(row)"
              >申请退库</el-button>
              <span v-else class="color-green">
                PC无可申请退库或已全部申请退库
              </span>
            </el-button-group>
          </template>
        </wz-table>
      </el-col>
    </el-row>

    <el-dialog
      v-if="materialRemoveFormVisible"
      ref="materialRemoveFormVisible"
      v-dialogDrag
      :close-on-click-modal="false"
      :visible.sync="materialRemoveFormVisible"
      width="40%"
    >
      <div slot="title" class="dialog-header">退库申请单</div>
      <edit-remove-material-dialog
        :prj-id="prjParams.prjId"
        :can-retreat-amount="canRetreatAmount"
        :current-row="currentRow"
        @submitSave="submitSave"
      />
    </el-dialog>
    <el-dialog
      ref="materialRemovalVisible"
      v-dialogDrag
      :close-on-click-modal="false"
      :visible.sync="materialRemovalVisible"
      width="90%"
    >
      <div slot="title" class="dialog-header">资源资产编码和标签合集</div>

      <material-code-label
        v-if="materialRemovalVisible"
        :current-row="currentRow"
      />
    </el-dialog>
    <el-dialog
      ref="cancelRetreatVisible"
      v-dialogDrag
      :close-on-click-modal="false"
      :visible.sync="cancelRetreatVisible"
      width="90%"
    >
      <div slot="title" class="dialog-header">物资退库申请单</div>
      <CancelRetreatApplyTable
        v-if="cancelRetreatVisible"
        ref="cancelRetreatVisible"
        :current-row="currentRow"
        :is-edit="isEdit&&metaEdit"
        :project-info="projectInfo"
        @removeMaterial="removeMaterialCallBack"
        @switch="handleSwitch"
      />
    </el-dialog>
    <el-dialog
      v-if="updateTypeDialog"
      ref="updateTypeDialog"
      v-dialogDrag
      :close-on-click-modal="false"
      :visible.sync="updateTypeDialog"
      width="40%"
    >
      <div slot="title" class="dialog-header">修改退库类型申请单</div>
      <edit-remove-material-dialog
        type="update"
        :prj-id="prjParams.prjId"
        :current-row="currentRow"
        :update-row="cancelRetreatRow"
        :can-retreat-amount="canRetreatAmount"
        @submitSave="submitSave"
      />
    </el-dialog>
  </div>
</template>
<script>
import { pushResourceAndFinance } from '@/api/acceptantce'

const UPDATE_REMOVE_TYPE_LEFT = [
    {
        label: '站址编码',
        prop: 'siteId',
        elProps: {
            width: '180px',
            'show-overflow-tooltip': true
        }
    },
    {
        label: '物料编码',
        prop: 'categoryCode',
        elProps: {
            width: '180px',
            'show-overflow-tooltip': true
        }
    },
    {
        label: '物料名称',
        prop: 'categoryName',
        elProps: {
            'show-overflow-tooltip': true
        }
    },
    {
        label: '物料精度',
        prop: 'spuUnitAcc',
        elProps: {
            'show-overflow-tooltip': true
        }
    },
    {
        label: '主设备标识',
        prop: 'spuMainName',
        elProps: {
            width: '100px',
            'show-overflow-tooltip': true
        }
    },
    {
        label: '源头赋码标识',
        prop: 'ifSourceName',
        elProps: {
            width: '180px',
            'show-overflow-tooltip': true
        }
    },
    {
        label: '已出库数量',
        prop: 'amount',
        elProps: {
            'show-overflow-tooltip': true
        }
    },
    {
        label: '申请退库总数',
        prop: 'retreatAmount',
        elProps: {
            'show-overflow-tooltip': true
        }
    },
    {
        label: '完成退库总数',
        prop: 'retreatRealAmount',
        elProps: {
            'show-overflow-tooltip': true
        }
    }
]
const UPDATE_REMOVE_TYPE_RIGHT = [
    {
        label: 'PC可申请退库数量',
        prop: 'canRetreatAmount',
        elProps: {
            width: '140px',
            'show-overflow-tooltip': true
        }
    },
    {
        label: 'APP可申请退库数量',
        prop: 'pcBanNum',
        elProps: {
            width: '140px',
            'show-overflow-tooltip': true
        }
    },
    {
        label: '操作',
        prop: 'operation',
        elProps: {
            width: '230px',
            'show-overflow-tooltip': true
        }
    },
    {
        label: '申领单号',
        prop: 'recipientApplyId',
        elProps: {
            width: '120px',
            'show-overflow-tooltip': true
        }
    },
    {
        label: '出库单号',
        prop: 'orderId',
        elProps: {
            width: '120px',
            'show-overflow-tooltip': true
        }
    },
    {
        label: '出库明细行号',
        prop: 'osDetailId',
        elProps: {
            width: '120px',
            'show-overflow-tooltip': true
        }
    },
    {
        label: '是否利旧资产',
        prop: 'outputType',
        elProps: {
            width: '120px',
            'show-overflow-tooltip': true
        }
    },
    {
        label: '规格型号',
        prop: 'formPattern',
        elProps: {
            width: '120px',
            'show-overflow-tooltip': true
        }
    },
    {
        label: '商品编码',
        prop: 'materialCode',
        elProps: {
            width: '120px',
            'show-overflow-tooltip': true
        }
    },
    {
        label: '商品名称',
        prop: 'materialName',
        elProps: {
            width: '120px',
            'show-overflow-tooltip': true
        }
    },
    {
        label: '资产编号',
        prop: 'assetCode',
        elProps: {
            width: '120px',
            'show-overflow-tooltip': true
        }
    },
    {
        label: '资产名称',
        prop: 'assetName',
        elProps: {
            width: '120px',
            'show-overflow-tooltip': true
        }
    },
    {
        label: '合同编号',
        prop: 'contractCode',
        elProps: {
            width: '120px',
            'show-overflow-tooltip': true
        }
    },
    {
        label: '供应商名称',
        prop: 'providerName',
        elProps: {
            width: '120px',
            'show-overflow-tooltip': true
        }
    },
    {
        label: '自定义规格',
        prop: 'dwjl',
        elProps: {
            width: '120px',
            'show-overflow-tooltip': true
        }
    },
    {
        label: '计量单位',
        prop: 'unit',
        elProps: {
            width: '120px',
            'show-overflow-tooltip': true
        }
    },
    {
        label: '不含税单价',
        prop: 'price',
        elProps: {
            width: '120px',
            'show-overflow-tooltip': true
        }
    },
    {
        label: '含税总金额',
        prop: 'totalTaxAmount',
        elProps: {
            width: '120px',
            'show-overflow-tooltip': true
        }
    },
    {
        label: '领用人',
        prop: 'receivePerson',
        elProps: {
            width: '120px',
            'show-overflow-tooltip': true
        }
    },
    {
        label: '出库时间',
        prop: 'osTime',
        elProps: {
            width: '120px',
            'show-overflow-tooltip': true
        }
    }
]
// 系统常量配置
import wzTable from './cTable'
import EditRemoveMaterialDialog from './editRemoveMaterialDialog.vue'
import materialCodeLabel from './materialCodeLabel.vue'
import CancelRetreatApplyTable from './cancelRetreatApplyTable.vue'
import {
    routineRetreatApply,
    equipTypeUpdateRetreat,
    getPrjInternalState,
    pushResource
} from '@/api/material'
import { disableScroll, enableScroll } from '@/utils'
// import { pushResourceAndFinance } from '@/api/acceptantce'
export default {
    name: 'RemoveMaterialsDetails',
    components: {
        wzTable,
        EditRemoveMaterialDialog,
        materialCodeLabel,
        CancelRetreatApplyTable
    },
    props: {
        flag: {
            type: Number,
            default: 1
        },
        tableData: {
            type: Array,
            default: () => []
        },
        projectInfo: {
            type: Object,
            default: () => ({})
        },
        prjParams: {
            type: Object,
            default: () => ({})
        },
        metaEdit: {
            type: Boolean,
            default: true
        }
    },
    data() {
        return {
            fileList: [],
            receiveDetailsData: {},
            designData: [],
            materialRemovalVisible: false,
            materialBackVisible: false,
            arrivalVisible: false,
            planGetTime: '',
            wzApplicationColumnLeft: [],
            wzApplicationColumnRight: [],
            nonarrivalNumForm: {
                nonarrivalNum: ''
            },
            materialsRemarks: '',
            form: {
                categoryCode: '',
                categoryName: '',
                applySno: '',
                orderId: ''
            },
            materialRemoveFormVisible: false,
            canRetreatAmount: 0,
            currentRow: [],
            cancelRetreatVisible: false,
            updateTypeDialog: false,
            cancelRetreatRow: [],
            prjInternalState: 0,
            isNewPrj: 0
            // materialRemovalVisible: false // 控制资源资产编码和标签合集
        }
    },
    computed: {
        query() {
            return this.$route.query
        },
        backMaterialState() {
            return !+this.prjInternalState
        },
        retreatAmount() {
            return (row) => {
                if (+row.errorPushCount > 0) {
                    return `${
                        row.retreatAmount
                    }(推送失败${+row.errorPushCount})`
                } else {
                    return row.retreatAmount
                }
            }
        },
        isEdit() {
            return !!+this.projectInfo?.isEdit
        },
        visibleDialog() {
            return (
                this.materialRemovalVisible ||
                this.cancelRetreatVisible ||
                this.materialRemoveFormVisible
            )
        },
        newPerissonShow(){
            return +this.prjInternalState===1&&+this.projectInfo?.isNewAcceptance===1&&+this.projectInfo?.acceptcheck===1
        }
    },
    watch: {
        tableData: {
            handler(newValue, oldValue) {
                this.designData = newValue
            },
            deep: true,
            immediate: true
        },
        updateTypeDialog(value) {
            this.cancelRetreatVisible = !value
        },
        visibleDialog(val) {
            if (!val) {
                enableScroll(window.top.document.body)
            }
        }
    },
    async created() {
        this.wzApplicationColumnLeft = JSON.parse(
            JSON.stringify(UPDATE_REMOVE_TYPE_LEFT)
        )
        this.wzApplicationColumnRight = JSON.parse(
            JSON.stringify(UPDATE_REMOVE_TYPE_RIGHT)
        )
        console.log('prjParams', this.prjParams)
        const res = await getPrjInternalState({ prjId: this.prjParams.prjId })
        if (+res.code === 200) {
            this.prjInternalState = res.data.internalState
            this.isNewPrj = res.data.isNewPrj
            console.log("=>>>",res.data,this.projectInfo);
        }
    },
    methods: {
        newPower(row,type){
            const show = +this.projectInfo.reState === 0 && +this.projectInfo.sjbgcheck === 0
            if (type === 'back') {
                return this.checkIsRetreat(row) && show
            } else {
                return row.canRetreatAmount > 0 && show
            }
        },
        // 是否利旧资产
        outputType(row) {
            if (+row.outputType === 25) {
                return '是'
            }
             if (+row.outputType === 9) {
                return '否'
            }
            return ''
        },
        // 判断是否有撤销退库的操作
        checkIsRetreat(row) {
            return row.retreatAmount - row.retreatRealAmount > 0
        },
        nonarrivalDisabled(row) {
            if (+row.noReceiveAmount) {
                return false
            }
            return true
        },

        // 点击出库数量
        handleMaterialRemoveList(row) {
            this.currentRow = row
            this.materialRemovalVisible = true
            this.dialogEl('materialRemovalVisible')
        },
        // 申请退库总数
        handleMaterialBackListVisible() {
            this.materialBackVisible = true
        },
        // 已贴标签数量
        handleArrivalVisible() {
            this.arrivalVisible = true
        },
        handleMaterialRemoveFormVisible(row) {
            console.log(row, 'rowrow')
            this.currentRow = row
            this.materialRemoveFormVisible = true
            this.canRetreatAmount = row.canRetreatAmount
            this.dialogEl('materialRemoveFormVisible')
        },
        // 撤销退库
        handleCancelRetreatApply(row) {
            this.currentRow = row
            this.cancelRetreatVisible = true
            this.dialogEl('cancelRetreatVisible')
        },
        // 搜索
        handleSearch() {
            this.$emit('search', this.form)
        },
        async handlePush() {
            const res = await pushResourceAndFinance({
                prjId: this.query.prjId
            })
            if (+res.code === 200) {
                this.$message.success('推送成功')
            }
        },
        removeMaterialCallBack() {
            this.handleSearch()
        },
        // 退库类型修改弹窗时触发
        handleSwitch(value, row) {
            this.cancelRetreatVisible = value
            this.cancelRetreatRow = row
            this.canRetreatAmount = +row.retreatAmount
            this.updateTypeDialog = !value
        },
        // 常规退库
        async submitSave(form, row) {
            const params = {
                bundingId: this.currentRow.bundingId,
                fieldProjectManager: this.currentRow.fieldProjectManager,
                materialCode: this.currentRow.materialCode,
                outputType: this.currentRow.outputType,
                pmsRetreatType: row.retreatDetailId ? this.cancelRetreatRow.pmsRetreat : '31',
                osDetailId: this.currentRow.osDetailId,
                sourceAssetCode: this.currentRow.sourceAssetCode || '',
                prjId: this.query.prjId,
                canRetreatAmount: this.currentRow.canRetreatAmount,
                ...form
            }
            if (row.retreatDetailId) {
                params.retreatDetailId = row.retreatDetailId
                params.sourceType = this.cancelRetreatRow.pmsRetreat
                const loading_ = this.$loading({
                    lock: true,
                    text: '退库类型修改中,请稍后...',
                    spinner: 'el-icon-loading'
                })
                try {
                    const res = await equipTypeUpdateRetreat(params)
                    if (+res.code === 200) {
                        this.$emit('removeMaterial')
                        loading_.close()
                        this.updateTypeDialog = false
                        this.$message.success('操作成功')
                    }
                } catch (error) {
                    loading_.close()
                } finally {
                    loading_.close()
                }
                return
            }

            const loading = this.$loading({
                lock: true,
                text: '提交退库申请中,请稍后...',
                spinner: 'el-icon-loading'
            })
            try {
                const res = await routineRetreatApply(params)
                if (+res.code !== 200) {
                  return Promise.reject(res)
        }
                this.materialRemoveFormVisible = false
                this.$emit('removeMaterial')
                loading.close()
            } catch (error) {
                console.log(error, 'error')
                loading.close()
            } finally {
                loading.close()
            }
        },
        dialogEl(refName) {
            // 将弹框挂载在最外层
            const contentBody = window.top.document.body
            this.$nextTick(() => {
                if (self !== top) {
                    const dialogModal = document.querySelector('.v-modal')
                    contentBody.appendChild(this.$refs[refName].$el)
                    contentBody.appendChild(dialogModal)
                }

                disableScroll(contentBody)
            })
        }
    }
}
</script>
<style scoped lang="scss">
.el-table th {
    padding: 0px 0;
    text-align: center;
    font-size: 12px;
    color: #333333;
    letter-spacing: 0;
}
.el-table td {
    padding: 0px 0;
    text-align: center;
    font-size: 2px;
    color: #333333;
    letter-spacing: 0;
}
.click-row {
    color: #53c7f8;
    cursor: pointer;
}
.materials-remark-wrapper {
    position: relative;
    border: 1px solid #ccc;
    padding-left: 10px;
    padding-right: 10px;
    padding-top: 20px;
    padding-bottom: 10px;
    &-title {
        position: absolute;
        left: 50%;
        top: -13px;
        background: #fff;
        font-weight: bold;
    }
}

.mt-10 {
    margin-top: 10px;
}
.mb-10 {
    margin-bottom: 10px;
}
.mr-5 {
    margin-right: 5px !important;
}
.flex-box {
    display: flex;
    width: 100%;
    align-items: center;

    &-left {
        margin-right: auto;
    }
}
.pms-el-datepicker {
    margin-left: 10px;
    margin-right: 10px;
    height: 24px;
    ::v-deep .el-input__inner {
        height: 24px;
    }
    ::v-deep .el-input__icon {
        line-height: 20px;
    }
}
.pb-5 {
    padding-bottom: 5px;
}
.color-green {
    color: #77dfaf;
}
.header-wrapper {
    width: 95%;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
::v-deep .el-pagination.is-background .el-pager li:not(.disabled).active {
    background-color: #f56c6c;
}
</style>
